package com.web.all.common.bean;

import java.util.concurrent.ConcurrentHashMap;

public class ChainContextHolder extends ConcurrentHashMap<String, Object> {

    protected static Class<? extends ChainContextHolder> contextClass = ChainContextHolder.class;

    protected static final ThreadLocal<? extends ChainContextHolder> THREAD_LOCAL = new InheritableThreadLocal<ChainContextHolder>() {
        @Override
        protected ChainContextHolder initialValue() {
            try {
                return contextClass.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    /**
     * Override the default ChainRequestContext
     *
     * @param clazz
     */
    public static void setContextClass(Class<? extends ChainContextHolder> clazz) {
        contextClass = clazz;
    }

    /**
     * Get the current ChainRequestContext
     *
     * @return the current ChainRequestContext
     */
    public static final ChainContextHolder getCurrentContext() {
        return THREAD_LOCAL.get();
    }

    /**
     * Unsets the threadLocal context. Done at the end of the request.
     *
     * @return
     */
    public void unset() {
        this.clear();
        THREAD_LOCAL.remove();
    }


}
